package backend.service.charisma;

import backend.model.admin.Employee;
import backend.model.charisma.CharismaWorkLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import shared.exceptions.CharismaConnectionDownException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CharismaWorkLogServiceImpl implements CharismaWorkLogService {

    @Autowired
    protected CharismaDao<CharismaWorkLog> charismaDao;

    @Override
    public CharismaWorkLog loadCharismaWorkLogForDateAndEmployee(Date date, Employee employee) throws CharismaConnectionDownException {
        List<CharismaWorkLog> result = new ArrayList<CharismaWorkLog>();

        try {
            result = charismaDao.findByNamedQueryAndParams("loadCharismaWorkLogForDateAndEmployeeIdentificationCard",
                new String[]{"date", "identificationCard"}, new Object[]{date, employee.getIdentificationCard()});
        } catch (DataAccessException dae) {
            throw new CharismaConnectionDownException(dae);
        }

        if (result.size() == 1) {
            return result.get(0);
        } else if (result.size() == 0) {
            return null;
        }
        throw new RuntimeException("More than one work log entry was found in Charisma for date " + date + " identification card " + employee.getIdentificationCard());
    }

    @Override
    public List<CharismaWorkLog> loadCharismaWorkLogForTimeIntervalAndEmployee(Date startDate, Date endDate, Employee employee) throws CharismaConnectionDownException {
        List<CharismaWorkLog> result = new ArrayList<CharismaWorkLog>();

        try {
            result = charismaDao.findByNamedQueryAndParams("loadCharismaWorkLogForTimeIntervalAndEmployeeIdentificationCard",
                new String[]{"startDate", "endDate", "identificationCard"}, new Object[]{startDate, endDate, employee.getIdentificationCard()});
        } catch (DataAccessException dae) {
            throw new CharismaConnectionDownException(dae);
        }
       return result;
    }
}
